<?php

namespace app\modules\fileuploads\models;

use Yii;

/**
 * This is the model class for table "uploads".
 *
 * @property string $sign
 * @property string $path
 * @property string $url
 * @property string $ext
 * @property integer $addtime
 * @property integer $uptime
 * @property integer $weight
 */
class Uploads extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'uploads';
    }

    public static function validFileType($type, &$allow){
        $arr = explode('/', $type);
        if(count($arr) < 2)
            return false;
        $type = $arr[1];
        if(in_array($type, $allow))
            return "/" . $arr[0] . "s";
        return false;
    }

    public static function generateDir($path, $baseUrl){
        if(!file_exists($path))
            mkdir($path, 0755);
        foreach(explode("/", substr($baseUrl, 1)) as $dir){
            $path .= "/" . $dir;
            if(!file_exists($path))
                mkdir($path, 0755);
        }

        return $path;

    }

    public static function getBaseUrlByDir($dir){
        $dir .= "/" . date('Ymd', time());
        return $dir;
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sign'], 'required'],
            [['addtime', 'uptime', 'weight'], 'integer'],
            [['sign'], 'string', 'max' => 32],
            [['path', 'url'], 'string', 'max' => 255],
            [['ext'], 'string', 'max' => 3]
        ];
    }

    public function getFileName(){
        return $this->$sign . "." . $this->ext;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'sign' => Yii::t('app', 'Sign'),
            'path' => Yii::t('app', 'Path'),
            'url' => Yii::t('app', 'Url'),
            'ext' => Yii::t('app', 'Ext'),
            'addtime' => Yii::t('app', 'Addtime'),
            'uptime' => Yii::t('app', 'Uptime'),
            'weight' => Yii::t('app', 'Weight'),
        ];
    }

    public function save($runValidation = true, $attributeNames = null){
        if($this->isNewRecord){
            $this->setAttribute('addtime', time());
            $this->setAttribute('weight', 0);
        }
        $this->setAttribute('uptime', time());
        return parent::save($runValidation, $attributeNames);
    }
}
